import { add, list, update } from '@/services/vehicle/bicycle';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import { PageContainer, ProDescriptions, ProTable } from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button, Drawer, Image, message } from 'antd';
import React, { useRef, useState } from 'react';
import EditModal from './components/EditModal';

const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [editModalOpen, handleEditModalOpen] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.RuleListItem>();

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  /**
   * @en-US Add node
   * @zh-CN 添加节点
   * @param fields
   */
  const handleSave = async (fields: any) => {
    const hide = message.loading('正在保存');
    console.log(fields);
    try {
      if (fields.id) {
        await update({ ...fields });
      } else {
        await add({ ...fields });
      }
      hide();
      message.success('Added successfully');
      return true;
    } catch (error) {
      hide();
      message.error('Adding failed, please try again!');
      return false;
    }
  };

  const columns: ProColumns<VEHICLE.Bicycle>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      width: 80,
      search: false,
    },
    {
      title: <FormattedMessage id="pages.vehicle.bicycle.plateNo" defaultMessage="Plate No" />,
      dataIndex: 'plateNo',
    },
    {
      title: <FormattedMessage id="pages.photo" defaultMessage="Photo" />,
      valueType: 'textarea',
      hideInSearch: true,
      render: (_, record) => {
        return (
          <Image
            width={80}
            src={
              record.images
                ? record.images[0]
                  ? record.images[0].url + '&width=500&height=500'
                  : ''
                : ''
            }
            fallback=""
          />
        );
      },
    },
    {
      title: <FormattedMessage id="pages.description" defaultMessage="Description" />,
      dataIndex: 'description',
      valueType: 'textarea',
    },
    {
      title: <FormattedMessage id="pages.vehicle.bicycle.baseFare" defaultMessage="Base Fare" />,
      dataIndex: 'baseFare',
      valueType: 'textarea',
    },
    {
      title: <FormattedMessage id="pages.vehicle.bicycle.price" defaultMessage="Price" />,
      dataIndex: 'price',
      valueType: 'textarea',
    },
    {
      title: <FormattedMessage id="pages.vehicle.bicycle.priceType" defaultMessage="Price Type" />,
      dataIndex: 'priceType',
      hideInForm: true,
      valueEnum: {
        1: {
          text: (
            <FormattedMessage id="pages.vehicle.bicycle.priceType.fixed" defaultMessage="Fixed" />
          ),
          status: 'Processing',
        },
        2: {
          text: (
            <FormattedMessage id="pages.vehicle.bicycle.priceType.time" defaultMessage="Time" />
          ),
          status: 'Success',
        },
      },
    },
    {
      title: <FormattedMessage id="pages.status" defaultMessage="Status" />,
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        0: {
          text: <FormattedMessage id="pages.vehicle.bicycle.status.idle" defaultMessage="idle" />,
          status: 'Processing',
        },
        1: {
          text: <FormattedMessage id="pages.vehicle.bicycle.status.lease" defaultMessage="lease" />,
          status: 'Success',
        },
        2: {
          text: (
            <FormattedMessage
              id="pages.vehicle.bicycle.status.abnormal"
              defaultMessage="abnormal"
            />
          ),
          status: 'Default',
        },
      },
    },
    {
      title: <FormattedMessage id="pages.createDate" defaultMessage="Create Date" />,
      dataIndex: 'createDate',
      valueType: 'dateTime',
    },
    {
      title: <FormattedMessage id="pages.updateDate" defaultMessage="Update Date" />,
      dataIndex: 'updateDate',
      valueType: 'dateTime',
    },
    {
      title: <FormattedMessage id="pages.option" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="modify"
          onClick={() => {
            setCurrentRow(record);
            handleEditModalOpen(true);
          }}
        >
          <FormattedMessage id="pages.modify" defaultMessage="modify" />
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.RuleListItem, API.PageParams>
        headerTitle={intl.formatMessage({
          id: 'pages.searchTable.title',
          defaultMessage: 'Enquiry form',
        })}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setCurrentRow(undefined);
              handleEditModalOpen(true);
            }}
          >
            <PlusOutlined /> <FormattedMessage id="pages.new" defaultMessage="New" />
          </Button>,
        ]}
        request={list}
        columns={columns}
      />
      <EditModal
        onSubmit={async (value) => {
          console.log(value);
          let success = await handleSave(value);
          if (success) {
            handleEditModalOpen(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        setEditModalOpen={async (open) => {
          if (!open) {
            setCurrentRow(undefined);
          }
          handleEditModalOpen(open);
        }}
        editModalOpen={editModalOpen}
        values={currentRow || {}}
      />
      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<API.RuleListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
